package com.ruibang.glass.produce.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruibang.glass.common.constants.RedisKey;
import com.ruibang.glass.produce.constant.Constants;
import com.ruibang.glass.produce.domain.req.DefectSampleReq;
import com.ruibang.glass.produce.domain.resp.DefectSampleRateChart;
import com.ruibang.glass.produce.entity.DefectSample;
import com.ruibang.glass.produce.entity.DefectSampleItem;
import com.ruibang.glass.produce.entity.DefectSampleItemDetail;
import com.ruibang.glass.produce.mapper.DefectSampleMapper;
import com.ruibang.glass.produce.service.DefectSampleItemDetailService;
import com.ruibang.glass.produce.service.DefectSampleItemService;
import com.ruibang.glass.produce.service.DefectSampleService;
import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 溶解缺陷取样 服务实现类
 * </p>
 *
 * @author songJinKang
 * @since 2024-04-28
 */
@Service
public class DefectSampleServiceImpl extends ServiceImpl<DefectSampleMapper, DefectSample> implements DefectSampleService {

    @Autowired
    private DefectSampleItemService defectSampleItemService;

    @Autowired
    private DefectSampleItemDetailService defectSampleItemDetailService;

    @Autowired
    private RedisSingleService redisService;

    @Override
    public DefectSample getDetail(String id) {
        DefectSample defectSample = this.getById(id);
        if (defectSample != null) {
            //获取取样项目
            List<DefectSampleItem> defectSampleItems = defectSampleItemService.getBySampleIds(Collections.singletonList(id));
            if (CollectionUtils.isNotEmpty(defectSampleItems)) {
                defectSample.setDefectSampleItems(defectSampleItems);
                //获取取样项目详情
                List<String> itemIds = defectSampleItems.stream().map(DefectSampleItem::getSampleItemId).collect(Collectors.toList());
                List<DefectSampleItemDetail> defectSampleItemDetailList = defectSampleItemDetailService.getBySampleItemIds(itemIds);
                if (CollectionUtils.isNotEmpty(defectSampleItemDetailList)) {
                    Map<String, List<DefectSampleItemDetail>> defectSampleItemDetailMap = defectSampleItemDetailList.stream().collect(Collectors.groupingBy(DefectSampleItemDetail::getSampleItemId));
                    for (DefectSampleItem defectSampleItem : defectSampleItems) {
                        defectSampleItem.setDefectSampleItemDetail(defectSampleItemDetailMap.get(defectSampleItem.getSampleItemId()));
                    }
                }
            }
        }
        return defectSample;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(String id) {
        //删除取样数据
        this.removeById(id);

        //删除具体样品数据
        List<DefectSampleItem> defectSampleItems = defectSampleItemService.getBySampleIds(Collections.singletonList(id));
        defectSampleItemService.removeBySampleId(id);

        //删除详情信息
        if (CollectionUtils.isNotEmpty(defectSampleItems)) {
            List<String> ids = defectSampleItems.stream().map(DefectSampleItem::getSampleItemId).collect(Collectors.toList());
            defectSampleItemDetailService.removeBySampleId(ids);
        }
    }

    @Override
    public IPage<DefectSample> pageQuery(DefectSampleReq defectSampleReq) {
        QueryWrapper<DefectSample> qw = new QueryWrapper<>();
        if (defectSampleReq.getStartTime() != null && defectSampleReq.getEndTime() != null) {
            qw.lambda().ge(DefectSample::getDataTime, defectSampleReq.getStartTime());
            qw.lambda().le(DefectSample::getDataTime, defectSampleReq.getEndTime());
        }
        qw.lambda().orderByDesc(DefectSample::getDataTime);
        Page<DefectSample> page = this.page(new Page<>(defectSampleReq.getPageNo(), defectSampleReq.getPageSize()), qw.lambda());
//        if (page != null && CollectionUtils.isNotEmpty(page.getRecords())) {
//            List<DefectSample> records = page.getRecords();
//            List<String> sampleIds = records.stream().map(DefectSample::getSampleId).collect(Collectors.toList());
//            List<DefectSampleItem> defectSampleItems = defectSampleItemService.getBySampleIds(sampleIds);
//            if (CollectionUtils.isNotEmpty(defectSampleItems)) {
//                Map<String, List<DefectSampleItem>> defectSampleItemMap = defectSampleItems.stream().collect(Collectors.groupingBy(DefectSampleItem::getSampleId));
//                for (DefectSample record : records) {
//                    record.setDefectSampleItems(defectSampleItemMap.get(record.getSampleId()));
//                }
//            }
//        }
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insert(DefectSample defectSample) {
        //保存分析取样记录
        if (StringUtils.isBlank(defectSample.getCreateUserName())) {
            Object userNameObj = redisService.hget(RedisKey.USER_GROUP_TYPE, defectSample.getCreateUserId());
            if (userNameObj != null && StringUtils.isNotBlank(userNameObj.toString())) {
                defectSample.setCreateUserName(userNameObj.toString());
            }
        }
        defectSample.setIsDelete(Constants.ZERO_STR);
        this.save(defectSample);

        //保存样品信息
        List<DefectSampleItem> defectSampleItems = defectSample.getDefectSampleItems();
        if (CollectionUtils.isNotEmpty(defectSampleItems)) {
            for (DefectSampleItem defectSampleItem : defectSampleItems) {
                defectSampleItem.setSampleId(defectSample.getSampleId());
                defectSampleItem.setDataTime(defectSample.getDataTime());
                defectSampleItem.setIsDelete(Constants.ZERO_STR);
            }
            defectSampleItemService.saveBatch(defectSampleItems);

            //保存样品详情信息
            List<DefectSampleItemDetail> detailList = new ArrayList<>();
            for (DefectSampleItem defectSampleItem : defectSampleItems) {
                List<DefectSampleItemDetail> defectSampleItemDetail = defectSampleItem.getDefectSampleItemDetail();
                if (CollectionUtils.isNotEmpty(defectSampleItemDetail)) {
                    for (DefectSampleItemDetail sampleItemDetail : defectSampleItemDetail) {
                        sampleItemDetail.setSampleItemId(defectSampleItem.getSampleItemId());
                        sampleItemDetail.setDataTime(defectSampleItem.getDataTime());
                        sampleItemDetail.setIsDelete(Constants.ZERO_STR);
                        sampleItemDetail.setDefectType(defectSampleItem.getDefectType());
                    }
                    detailList.addAll(defectSampleItemDetail);
                }
            }
            defectSampleItemDetailService.saveBatch(detailList);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(DefectSample defectSample) {
        //修改取样记录
        Object userNameObj = redisService.hget(RedisKey.USER_GROUP_TYPE, defectSample.getCreateUserId());
        if (userNameObj != null && StringUtils.isNotBlank(userNameObj.toString())) {
            defectSample.setCreateUserName(userNameObj.toString());
        }
        this.updateById(defectSample);

        //修改样品信息
        List<DefectSampleItem> defectSampleItems = defectSample.getDefectSampleItems();
        defectSampleItemService.deleteBySampleId(defectSample.getSampleId());
        if (CollectionUtils.isNotEmpty(defectSampleItems)) {
            List<String> oldSampleItemIds = defectSampleItems.stream().map(DefectSampleItem::getSampleItemId).collect(Collectors.toList());
            defectSampleItems.forEach(e -> e.setSampleItemId(null));
            defectSampleItemService.saveBatch(defectSampleItems);

            //修改样品详情信息
            defectSampleItemDetailService.deleteBySampleItemId(oldSampleItemIds);
            List<DefectSampleItemDetail> detailList = new ArrayList<>();
            for (DefectSampleItem defectSampleItem : defectSampleItems) {
                List<DefectSampleItemDetail> defectSampleItemDetails = defectSampleItem.getDefectSampleItemDetail();
                if (CollectionUtils.isNotEmpty(defectSampleItemDetails)) {
                    for (DefectSampleItemDetail sampleItemDetail : defectSampleItemDetails) {
                        sampleItemDetail.setId(null);
                        sampleItemDetail.setSampleItemId(defectSampleItem.getSampleItemId());
                        sampleItemDetail.setDataTime(defectSampleItem.getDataTime());
                        sampleItemDetail.setDefectType(defectSampleItem.getDefectType());
                    }
                    detailList.addAll(defectSampleItemDetails);
                }
            }
            defectSampleItemDetailService.saveBatch(detailList);
        }
    }

    @Override
    public DefectSampleRateChart rateChart(DefectSampleReq defectSampleReq) {
        QueryWrapper<DefectSample> qw = new QueryWrapper<>();
        if (defectSampleReq.getStartTime() != null && defectSampleReq.getEndTime() != null) {
            qw.lambda().ge(DefectSample::getDataTime, defectSampleReq.getStartTime());
            qw.lambda().le(DefectSample::getDataTime, defectSampleReq.getEndTime());
        }
        qw.lambda().orderByDesc(DefectSample::getDataTime);
        List<DefectSample> data = this.list(qw);
        DefectSampleRateChart defectSampleRateChart = new DefectSampleRateChart();
        if (CollectionUtils.isNotEmpty(data)) {
            //采集时间
            List<String> dataTime = data.stream().map(e -> e.getDataTime().format(Constants.DATE_TIME_FORMATTER)).collect(Collectors.toList());
            defectSampleRateChart.setDataTime(dataTime);
            //气泡
            List<Double> bubbleRate = data.stream().map(DefectSample::getBubbleRate).filter(Objects::nonNull).collect(Collectors.toList());
            defectSampleRateChart.setBubbleRate(bubbleRate);
            //铂金
            List<Double> ptRate = data.stream().map(DefectSample::getPtRate).filter(Objects::nonNull).collect(Collectors.toList());
            defectSampleRateChart.setPtRate(ptRate);
            //结石
            List<Double> stoneRate = data.stream().map(DefectSample::getStoneRate).filter(Objects::nonNull).collect(Collectors.toList());
            defectSampleRateChart.setStoneRate(stoneRate);
            //总
            List<Double> totalRate = data.stream().map(DefectSample::getTotalRate).filter(Objects::nonNull).collect(Collectors.toList());
            defectSampleRateChart.setTotalRate(totalRate);
        }
        return defectSampleRateChart;
    }

    @Override
    public Map<String, Object> analysisChart(DefectSampleReq defectSampleReq) {
        QueryWrapper<DefectSampleItemDetail> qw = new QueryWrapper<>();
        if (defectSampleReq.getStartTime() != null && defectSampleReq.getEndTime() != null) {
            qw.lambda().ge(DefectSampleItemDetail::getDataTime, defectSampleReq.getStartTime());
            qw.lambda().le(DefectSampleItemDetail::getDataTime, defectSampleReq.getEndTime());
        }
        qw.lambda().eq(DefectSampleItemDetail::getDefectType, defectSampleReq.getDefectType());
        qw.lambda().orderByAsc(DefectSampleItemDetail::getDataTime);
        List<DefectSampleItemDetail> defectSampleItemDetails = defectSampleItemDetailService.list(qw);
        if (CollectionUtils.isNotEmpty(defectSampleItemDetails)) {
            Map<String, Object> dataMap = new LinkedHashMap<>();
            //采集时间
            List<String> collectTime = defectSampleItemDetails.stream().map(e -> e.getDataTime().format(Constants.DATE_TIME_FORMATTER)).distinct().collect(Collectors.toList());
            dataMap.put("collectTime", collectTime);
            //设置分类数据
            Map<String, List<DefectSampleItemDetail>> defectSampleItemMap = defectSampleItemDetails.stream().collect(Collectors.groupingBy(DefectSampleItemDetail::getClassification));
            defectSampleItemMap.forEach((k, v) -> {
                if (CollectionUtils.isNotEmpty(v)) {
                    List<Integer> data = v.stream().sorted(Comparator.comparing(DefectSampleItemDetail::getDataTime)).map(DefectSampleItemDetail::getNum).collect(Collectors.toList());
                    dataMap.put(k, data);
                }
            });
            return dataMap;
        }
        return Collections.emptyMap();
    }


}
